package com.zj.open.wechat.service.processor;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.zj.open.wechat.dao.MessageMapper;
import com.zj.open.wechat.dao.UserMapper;
import com.zj.open.wechat.dto.msg.LinkMessage;
import com.zj.open.wechat.model.Message;
import com.zj.open.wechat.model.User;

@Component
public class LinkMessageProcessor extends MessageProcessor<LinkMessage> {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    UserMapper userMapper;
    @Autowired
    MessageMapper messageMapper;

    @Override
    public void process(LinkMessage message) {
        if (handlePuFa(message)) {

        } else {
            logger.info(JSON.toJSONString(message));
        }
    }

    Pattern pufa = Pattern.compile("https://weixin.spdbccc.com.cn/spdbcccWeChatPageRedPackets/StatusDistrubServlet.do\\?(\\S*)");
    Pattern pufaDesc = Pattern.compile("(\\S+)分享了浦发红包，快来开红包，天天享鸿运！");

    boolean handlePuFa(LinkMessage message) {
        Matcher m = pufa.matcher(message.getUrl());
        if (m.matches()) {
            String parameters = m.group(1);
            Map<String, String> kv = new HashMap<String, String>();
            for (String param : parameters.split("&")) {
                String[] pp = param.split("=");
                kv.put(pp[0], pp[1]);
            }
            Matcher matcher = pufaDesc.matcher(message.getDescription());
            // 周光进分享了浦发红包，快来开红包，天天享鸿运！
            if (message.getTitle().equals("抢红包活动") && matcher.matches()) {
                User user = userMapper.selectByOpenId(message.getFromUserName());
                user.setUserName(matcher.group(1));
                userMapper.updateByPrimaryKeySelective(user);

                Message msg = new Message();
                msg.setMsgId(message.getMsgId());
                msg.setProcessed(Boolean.TRUE);
                messageMapper.updateByPrimaryKeySelective(msg);
                return true;
            }
        }
        return false;
    }

}